#!/bin/bash

# 确保脚本在出错时停止执行
set -e

# 拉取最新的 git 代码
echo "Running git pull..."
git pull

# 设置 Docker 镜像名称和标签
IMAGE_NAME_TAG=world_info:v1

# 构建 Docker 镜像
echo "Building Docker image ${IMAGE_NAME_TAG}..."
docker build -t ${IMAGE_NAME_TAG} .

# 登录到 Docker Registry
echo "Logging into Docker registry harbor.laisontech.com..."
docker login harbor.laisontech.com

# 给 Docker 镜像打上标签
echo "Tagging the image..."
docker tag ${IMAGE_NAME_TAG} harbor.laisontech.com/lapis/${IMAGE_NAME_TAG}

# 推送镜像到 Harbor
echo "Pushing the image to harbor..."
docker push harbor.laisontech.com/lapis/${IMAGE_NAME_TAG}

# 删除world-info的部署
echo "Removing deployment..."
kubectl -n lapis-lab delete deploy world-info

# 应用 Kubernetes 部署
echo "Applying Kubernetes deployment..."
kubectl apply -n lapis-lab -f deploy.yaml

# 退出docker登录
echo "Logout harbor..."
docker logout

# 删除本地的 Docker 镜像
echo "Removing local Docker image ${IMAGE_NAME_TAG}..."
docker rmi -f ${IMAGE_NAME_TAG}

# 删除 Harbor 上的 Docker 镜像
echo "Removing Harbor image..."
docker rmi -f harbor.laisontech.com/lapis/${IMAGE_NAME_TAG}

echo "Deployment complete!"
